package com.cll.learn.cas.demo02;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2021/5/15 11:02
 */
public class RechargeThread implements Runnable {

    private final User user;
    private final int stamped;

    public RechargeThread(User user, int stamped) {
        this.user = user;
        this.stamped = stamped;
    }

    @Override
    public void run() {
        // 保持持续后台充值
        while (true) {
//            System.out.println("外层用来保证一直检测充值");
            // 用来结束当前充值的检测
            while (true) {
//                System.out.println("内层用来保证，必须让金额达到不需要充值的程度 > 20");
                Integer currentMoney = user.getMoney().getReference();
                if (currentMoney < 20) {
                    if (user.getMoney().compareAndSet(currentMoney, currentMoney + 20, stamped, stamped + 1)){
                        System.out.println("===>>> 当前用户余额 = " + currentMoney + "：充值之后余额 = " + user.getMoney().getReference() + ":版本号 = " + user.getMoney().getStamp());
                        break;
                    } else {
//                        System.out.println("===>>> 账户已经充值过了版本号。余额" + user.getMoney().getStamp() + ": " + user.getMoney().getReference());
//                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }
}
